<template>
  <div class="md-upload-card-img-base">
    <div class="md-upload-container" v-if="multiple">
      <ul class="md-file-list">
        <slot></slot>
        <li v-for="(item,index) in fileList" :key="index" :class="{'cover':item.isCover && cover}" @mouseover="handleMouseover(item)">
          <img :src="item.url" />

          <p class="loading" v-if="loading"><i class="el-icon-loading"></i>上传中</p>

          <div class="mask">
            <span @click="handleSetCover(item)" v-if="cover"><i class="el-icon-magic-stick"></i>设为封面</span>
            <span @click="handleFileRemove(item)"><i class="el-icon-delete-solid"></i>删除</span>
            <span>
              <el-upload :action="action" name="file" :headers="headers" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUploadReloadSuccess">
                <p>
                  <i class="el-icon-refresh-left"></i>重新上传
                </p>
              </el-upload>
            </span>
          </div>
        </li>
        <el-upload :action="action" name="file" :headers="headers" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess">
          <i slot="default" class="el-icon-plus"></i>

          <p class="loading" v-if="loading"><i class="el-icon-loading"></i>上传中</p>

          <p class="label">{{label}}</p>
        </el-upload>
      </ul>
    </div>

    <div class="md-upload-container" v-if="!multiple">
      <ul class="md-file-list">
        <el-upload :class="{ 'el-upload-single': fileList.length>0 }" :action="action" name="file" :headers="headers" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess">
          <img :src="fileList[0].url" v-if="fileList.length>0" />
          <p v-if="fileList.length>0" class="label1">
            <i class="el-icon-upload"></i>重新上传
          </p>

          <template v-if="fileList.length===0">
            <i slot="default" class="el-icon-plus"></i>
            <p class="label">{{label}}</p>
          </template>
        </el-upload>
      </ul>
    </div>

    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="ADOUV">
    </el-dialog>
  </div>
</template>

<script>
import { mdApiBase } from '../../../ddd/config.service'
export default {
  name: 'MdUploadCardImgBaseComponent',
  props: {
    label: {
      type: String,
      default: '添加轮播图'
    },
    /**
     * fileList
     * @param url
     * @param name
     * @param webUrl
     */
    value: [Array, Object],
    multiple: {
      type: Boolean,
      default: false
    },
    cover: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      action: `${mdApiBase}/common/upload`,
      headers: {
        Authorization: this.$local.getItem('Authorization')
      },
      dialogImageName: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      currentFile: null,
      loading: false
    }
  },
  watch: {
    value: {
      handler (val) {
        if (this.multiple) {
          if (val && val.length > 0) {
            this.fileList = val
          } else {
            this.fileList = []
          }
        } else {
          if (val) {
            this.fileList = []
            this.fileList.push(val)
          } else {
            this.fileList = []
          }
        }
      },
      deep: true,
      immediate: true
    },
    cover: {
      handler (val) {
        if (!val && this.fileList.length > 0) {
          this.fileList.forEach((item) => (item.isCover = false))
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      if (this.multiple) {
        if (this.value && this.value.length > 0) {
          this.fileList = this.value
        } else {
          this.fileList = []
        }
      } else {
        if (this.value) {
          this.fileList = []
          this.fileList.push(this.value)
        } else {
          this.fileList = []
        }
      }
    })
  },
  methods: {
    handleMouseover (item) {
      this.currentFile = item
    },
    // 上传前
    handleBeforeUpload () {
      this.loading = true
      return true
    },
    // 重新上传，上传成功
    handleUploadReloadSuccess (res) {
      if (res.code === 200) {
        if (this.multiple) {
          const fileList = this.fileList
          fileList.forEach((f) => {
            if (f.id === this.currentFile.id) {
              f.url = res.url
            }
          })
          this.$emit('input', [...fileList])
        }

        this.loading = false
        return
      }

      if (res.code === 401) {
        this.loading = false
        this.$local.clear()
        this.$message.error('登录超时')
        this.$router.push('/login')
        return
      }

      this.loading = false

      this.$message.error(res.msg)
    },
    // 上传成功
    handleUploadSuccess (res) {
      if (res.code === 200) {
        if (!this.multiple) {
          this.fileList = []
        }

        this.fileList.push({
          id: this.fileList.length + 1,
          url: res.url,
          type: 'img',
          isCover: this.multiple ? false : true
        })

        if (!this.multiple) {
          this.$emit('input', { id: 1, url: res.url, type: 'img', isCover: true })
        } else {
          this.$emit('input', [...this.fileList])
        }

        this.loading = false

        return
      }

      if (res.code === 401) {
        this.loading = false
        this.$local.clear()
        this.$message.error('登录超时')
        this.$router.push('/login')
        return
      }

      this.loading = false

      this.$message.error(res.msg)
    },
    // 设为封面
    handleSetCover (item) {
      item.isCover = true
      const fileList = this.fileList
      fileList.forEach((l) => {
        if (l.id !== item.id) {
          l.isCover = false
        }
      })
      this.$emit('input', [...fileList])
    },
    // 删除图片
    handleFileRemove (item) {
      const index = this.fileList.findIndex((e) => e.id === item.id)

      this.fileList.splice(index, 1)

      const fileList = this.fileList
      this.$emit('input', [...fileList])
    }
  }
}
</script>

<style lang="less" scoped>
.md-upload-card-img-base {
  width: 100%;
  box-sizing: border-box;
  .md-upload-container {
    .md-file-list {
      display: flex;
      align-items: flex-start;
      flex-wrap: wrap;
      /deep/ .el-upload-single {
        .el-upload {
          line-height: 120px !important;
        }
      }
      ::v-deep .el-upload {
        display: block !important;
        width: 120px;
        height: 120px;
        line-height: normal !important;
        border: 1px dashed #dcdfe6;
        border-radius: 3px;
        margin: 0px !important;
        cursor: pointer;
        position: relative;

        img {
          width: auto;
          height: auto;
          max-width: 100%;
          max-height: 100%;
        }

        .label1 {
          display: none;
          position: absolute;
          left: 0px;
          top: 0px;
          z-index: 10;
          width: 100%;
          height: 100%;
          line-height: 120px;
          background-color: rgba(#000, 0.5);
          color: @md-primary-acolor;
        }

        .loading {
          position: absolute;
          top: 0px;
          left: 0px;
          width: 100%;
          height: 100%;
          line-height: 120px;
          background-color: rgba(#000, 0.5);
          font-size: 14px;
          color: #fff;
        }

        &:hover {
          color: @md-primary-acolor !important;
          .label1 {
            display: block;
          }
          .label {
            color: @md-primary-acolor !important;
          }
        }

        .el-icon-plus {
          margin-top: 30px;
        }
        .label {
          font-size: 12px;
          color: #999;
          padding-top: 10px;
        }
      }
      li {
        width: 120px;
        height: 120px;
        line-height: 120px;
        border: 1px dashed #dcdfe6;
        border-radius: 3px;
        margin-right: 10px;
        margin-bottom: 10px;
        text-align: center;
        position: relative;
        overflow: hidden;
        &.cover {
          &::before {
            content: ' ';
            display: block;
            width: 35px;
            height: 31px;
            background-image: url();
            background-repeat: no-repeat;
            background-position: center center;
            background-size: 100%;
            position: absolute;
            left: 0px;
            top: 0px;
            top: 3;
          }
        }

        &:hover {
          .mask {
            display: block;
          }
        }

        img {
          width: auto;
          height: auto;
          max-width: 100%;
          max-height: 100%;
        }

        .loading {
          position: absolute;
          top: 0px;
          left: 0px;
          width: 100%;
          height: 100%;
          line-height: 120px;
          background-color: rgba(#000, 0.5);
          font-size: 14px;
          color: #fff;
        }

        .mask {
          display: none;
          position: absolute;
          top: 0px;
          left: 0px;
          z-index: 10;
          width: 100%;
          height: 100%;
          line-height: normal !important;
          background-color: rgba(#000, 0.5);
          padding-top: 15px;
          span {
            display: block;
            width: 100%;
            height: 30px;
            line-height: 30px;
            text-align: center;
            font-size: 15px;
            color: rgba(#fff, 0.8);
            cursor: pointer;
            &:hover {
              color: rgba(#fff, 0.6);
            }
            i {
              margin-right: 10px;
            }
            /deep/ .el-upload {
              border: none !important;
              p {
                font-size: 15px;
                color: rgba(#fff, 0.8);
                &:hover {
                  color: rgba(#fff, 0.6);
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
